package homework04.test03;


public class TicketSell01 implements Runnable {
    // 声明ticketNum, 记录火车票张数
    private int ticketNum = 100;

    @Override
    public void run() {

        while (true) {

            synchronized (this) {
                //唤醒其他线程; 因为一共有3个线程, 所以使用notifyAll
                notifyAll();
                if (ticketNum > 0) {// 如果剩余票数大于0, 才能继续卖票
                    ticketNum--; // 剩余票数减1
                    System.out.println(Thread.currentThread().getName() + "卖掉了一张票, 剩余票数:" + ticketNum);
                    try {
                        // 休眠100毫秒
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        //调用wait方法, 进入阻塞状态
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out.println("票已卖光");
                    break;
                }
            }
        }
    }

    public static void main(String[] args) {
        //声明实现了Runnable接口的对象
        TicketSell01 ticket = new TicketSell01();
        //创建线程对象
        Thread t1 = new Thread(ticket);
        //设置线程名称
        t1.setName("窗口1");
        t1.start();

        Thread t2 = new Thread(ticket);
        t2.setName("窗口2");
        t2.start();

        Thread t3 = new Thread(ticket);
        t3.setName("窗口3");
        t3.start();

        try {
            //将3个线程加入主线程等待
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
